﻿using GalaSoft.MvvmLight.Messaging;
using JiveMessenger.Models;
using JiveMessenger.ViewModels;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Animation;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkID=390556

namespace JiveMessenger.Views
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class ManageGroupPage : BasicPage
    {
        private IEnumerable<IChatGroup> _chatGroup;
        public IEnumerable<IChatGroup> ChatGroups
        {
            get { return _chatGroup; }
            set
            {
                if (_chatGroup != value)
                {
                    _chatGroup = value;
                    RaisePropertyChanged("ChatGroups");
                }
            }
        }

        private IChatGroup _selectedGroup;
        public IChatGroup SelectedGroup
        {
            get { return _selectedGroup; }
            set
            {
                if (_selectedGroup != value)
                {
                    _selectedGroup = value;
                    RaisePropertyChanged("SelectedGroup");
                }
            }
        }


        public ManageGroupPage()
        {
            this.InitializeComponent();
            this.DataContext = this;

            Messenger.Default.Register<NotificationMessage>(this, msg =>
                {
                    switch (msg.Notification)
                    {
                        case "UpdateMyGroups":
                            var oldSelectedGroup = this.SelectedGroup;
                            Messenger.Default.Send(new NotificationMessageAction<IContact>(this, ViewModelContactList.MessengerCommands.GetCurrentUserContact.ToString(), contact =>
                            {
                                this.ChatGroups = contact.ChatGroups;
                                if (this.ChatGroups.Contains(oldSelectedGroup))
                                    this.SelectedGroup = oldSelectedGroup;
                                else
                                    this.SelectedGroup = this.ChatGroups.FirstOrDefault();
                            }));
                            break;
                    }
                });
        }


        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.
        /// This parameter is typically used to configure the page.</param>
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            Tuple<bool, IChatGroup> param = e.Parameter as Tuple<bool, IChatGroup>;

            if (param == null || (bool)param.Item1 == false)
            {
                await StatusBar.GetForCurrentView().HideAsync();
                await Task.Delay(800);
                Storyboard sb = this.Resources["ShowPageHeaderAnim"] as Storyboard;
                sb.Begin();
            }
            else
            {
                this.TextBoxPageHeader.Opacity = 1;
            }

            this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
                {
                    Messenger.Default.Send(new NotificationMessageAction<IContact>(this, ViewModelContactList.MessengerCommands.GetCurrentUserContact.ToString(), contact =>
                        {
                            this.ChatGroups = contact.ChatGroups;
                        }));
                    if (this.ChatGroups != null)
                    {
                        await Task.Delay(100);
                        if (param == null || param.Item2 == null)
                            this.SelectedGroup = this.ChatGroups.FirstOrDefault();
                        else
                        {
                            this.SelectedGroup = param.Item2;
                        }
                    }
                });

        }

        protected override async void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            //if (!(e.Content is GroupAndContactNavigationPage))
            //    await StatusBar.GetForCurrentView().ShowAsync();
        }

        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems != null && e.AddedItems.Count > 0)
            {
                ViewModelLocator locator = Application.Current.Resources["Locator"] as ViewModelLocator;
                IChatGroup grp = e.AddedItems[0] as IChatGroup;

                this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
                 {
                     await Task.Delay(200);
                     this.ManageGroupControl.DataContext = new ViewModelManageGroup(locator.CurrentClient, locator.NavService, grp);
                 });
            }

        }

        private void BasicPage_Loaded(object sender, RoutedEventArgs e)
        {
            Window.Current.Activated += Current_Activated;
        }

        private void BasicPage_Unloaded(object sender, RoutedEventArgs e)
        {
            Window.Current.Activated -= Current_Activated;
        }

        async void Current_Activated(object sender, Windows.UI.Core.WindowActivatedEventArgs e)
        {
            if (e.WindowActivationState == Windows.UI.Core.CoreWindowActivationState.Deactivated)
                this.TextBoxPageHeader.Opacity = 0;
            else
            {
                await StatusBar.GetForCurrentView().HideAsync();
                await Task.Delay(800);
                Storyboard sb = this.Resources["ShowPageHeaderAnim"] as Storyboard;
                sb.Begin();
            }
        }

        private void ManageGroupControl_DataContextChanged(FrameworkElement sender, DataContextChangedEventArgs args)
        {
            if (args.NewValue != null && args.NewValue is IViewModelManageGroup)
            {
                ViewModelLocator locator = (ViewModelLocator)Application.Current.Resources["Locator"];

                IViewModelManageGroup vm = (IViewModelManageGroup)args.NewValue;
                this.AppbarButtonRenameGroup.IsEnabled = true;
                this.AppbarButtonRenameGroup.Command = vm.RenameGroupCommand;
                this.AppbarButtonRenameGroup.CommandParameter = this.SelectedGroup;

                this.AppbarButtonDeleteGroup.IsEnabled = true;
                if (vm.DeleteGroupCommand.CanExecute(this.SelectedGroup))
                {
                    this.AppbarButtonDeleteGroup.Command = vm.DeleteGroupCommand;
                    this.AppbarButtonDeleteGroup.CommandParameter = this.SelectedGroup;
                    this.AppbarButtonDeleteGroup.Icon = new SymbolIcon(Symbol.Delete);
                    this.AppbarButtonDeleteGroup.Label = "Delete";
                }
                else
                {
                    this.AppbarButtonDeleteGroup.Command = locator.ViewModelContactList.LeaveGroupCommand;
                    this.AppbarButtonDeleteGroup.CommandParameter = this.SelectedGroup;
                    this.AppbarButtonDeleteGroup.Icon = new SymbolIcon(Symbol.LeaveChat);
                    this.AppbarButtonDeleteGroup.Label = "Leave";
                }

                this.AppbarButtonRefreshGroup.IsEnabled = true;
                this.AppbarButtonRefreshGroup.Command = vm.RefreshMembersCommand;

                this.AppbarButtonInviteToGroupCommand.IsEnabled = true;
                this.AppbarButtonInviteToGroupCommand.Command = locator.ViewModelContactList.InviteContactToGroupCommand;
                this.AppbarButtonInviteToGroupCommand.CommandParameter = this.SelectedGroup;

                this.AppBarToggleButtonBlockGroup.IsEnabled = true;

                this.AppBarToggleButtonBlockGroup.Command = locator.ViewModelContactList.BlockGroupCommand;
                this.AppBarToggleButtonBlockGroup.CommandParameter = this.SelectedGroup;

                var isGroupBlockedBinding = new Binding
                {
                    Path = new PropertyPath("IsBlocked"),
                    Mode = BindingMode.OneWay,
                    Source = vm.ChatGroup
                };
                var isCheckedProperty = AppBarToggleButton.IsCheckedProperty;
                this.AppBarToggleButtonBlockGroup.SetBinding(isCheckedProperty, isGroupBlockedBinding);

            }
            else
            {
                this.AppbarButtonRenameGroup.IsEnabled = false;
                this.AppbarButtonDeleteGroup.IsEnabled = false;
                this.AppbarButtonRefreshGroup.IsEnabled = false;
                this.AppbarButtonInviteToGroupCommand.IsEnabled = false;
            }
        }
    }
}
